package cn.peach.hrm.exception;

import cn.peach.hrm.constants.ErrorCode;
import cn.peach.hrm.util.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

// 全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = GlobalException.class)
    public AjaxResult globalExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder sB = new StringBuilder();
        allErrors.forEach(error ->{
            sB.append(error.getDefaultMessage()).append(";");
        });
        return AjaxResult.me().setSuccess(false).setMessage(sB.toString());
    }

    // 参数校验异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidException(GlobalException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }

    // 捕获其他异常
    @ExceptionHandler(value = Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(ErrorCode.SYSTEM_ERROR_EXCEPTION.getFullMessage());
    }
}
